local remain_inventory_key = KEYS[1]
local user_purchased_key = KEYS[2]
local purchase_amount = tonumber(ARGV[1])
local purchase_limit = tonumber(ARGV[2])

-- 1. 检查购买件数是否合法
if purchase_amount <= 0 then
    return -1  -- 表示购买件数无效
end

-- 2. 获取当前库存数量并检查库存数据是否存在
local remain_inventory = redis.call('get', remain_inventory_key)
if not remain_inventory then
    return -2  -- 表示库存数据不存在
end

remain_inventory = tonumber(remain_inventory)

-- 3. 检查库存是否足够
if remain_inventory <= 0 then
    return -3  -- 表示库存不足
end

-- 4. 检测库存是否足够
if remain_inventory < purchase_amount then
    return -4  -- 表示库存不足以满足减扣请求
end

-- 5. 用户购限逻辑
-- 获取用户已购买当前商品的数量
local current_user_purchased = redis.call('get', user_purchased_key)
if not current_user_purchased then
    current_user_purchased = 0  -- 如果不存在，设为0
else
    current_user_purchased = tonumber(current_user_purchased)
end
if current_user_purchased + purchase_amount > purchase_limit then
    return -5  -- 表示超过限购上限
end

-- 6. 执行库存更新
return redis.call('decrby', remain_inventory_key, purchase_amount)